package com.dtcnet.skmvp.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.viewbinding.ViewBinding;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

public abstract class SkBaseAdapter<T> extends BaseAdapter implements LifecycleObserver {

    protected List<T> mBeans;

    public SkBaseAdapter(@NotNull Context mContext) {
        ((LifecycleOwner) mContext).getLifecycle().addObserver(this);
    }

    public void reloadData(List<T> beans) {
        if (mBeans == null) {
            mBeans = new ArrayList<>();
        } else {
            mBeans.clear();
        }

        if (beans != null && beans.size() > 0) {
            mBeans.addAll(beans);
        }

        notifyDataSetChanged();
    }

    public List<T> getData() {
        return mBeans == null ? new ArrayList<>() : mBeans;
    }

    @Override
    public Object getItem(int position) {
        return mBeans.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getCount() {
        return mBeans != null ? mBeans.size() : 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            ViewBinding binding = getLayout(parent.getContext());
            convertView = binding.getRoot();
            convertView.setTag(getViewHolder(binding));
        }

        ((BaseHolder) convertView.getTag()).setData(convertView, mBeans.get(position), position);

        return convertView;
    }

    protected abstract ViewBinding getLayout(Context context);

    protected abstract BaseHolder getViewHolder(ViewBinding binding);

    protected void onDestroy() {
        mBeans = null;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    protected void onDestroy(LifecycleOwner owner) {
        onDestroy();
        owner.getLifecycle().removeObserver(this);
    }

    protected abstract class BaseHolder {
//        public BaseHolder(ViewBinding binding) {
//        }

        public abstract void setData(View view, T bean, int position);
    }

}
